import HttpProxy from '@helpers/HttpProxy'
import { ReactComponentExt } from '@helpers/ReactExt'
import { storage } from '@helpers/storage'
import utils from '@helpers/utils'
import { BaseProps } from '@store/store'
import { Button, Card, Form, Icon, Input } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import React from 'react'
import * as styles from './login.less'

export interface LoginProps extends FormComponentProps, BaseProps {
}

// createElement => ReactElement

interface LoginState {
  loading: boolean
  m: number
}

const { Provider, Consumer } = React.createContext(10)

const c = () => {
  return (
    <Consumer>
      {(value) => {
        console.log(value)
        return <></>
      }}
    </Consumer>
  )
}

// 向下取整: 位运算 [ | ]:
// 0.4 | 0 => 0; 2.3 | 0 => 2

export class Login extends ReactComponentExt<LoginProps, LoginState> {

  public name!: string
  private divRef!: React.RefObject<HTMLDivElement | null>
    // private divRef!: HTMLDivElement | null

  public init(): void {
    this.state = {
      loading: false,
      m: 0
    }

    this.handleSubmit = this.handleSubmit.bind(this)
    this.initReactRef()
  }

  public componentDidMount() {
    // let a = 1
    // setInterval(() => {
    //   this.setState({ m: a++ })
    // }, 2000)
    // ref={this.divRef}
    // ref={(node) => this.funRef = node}
    console.log(this.divRef, 1)
  }

  public render() {
    const { getFieldDecorator } = this.props.form
    const { loading } = this.state
    return (
      <Provider value={this.state.m}>
        <div className={styles.loginPage} ref={this.divRef}>
          {c()}
          <span>{this.name}</span>
          <Card title='登录舞蹈学校管理后台' className={styles.antCardCustom}>
            <Form layout='vertical' onSubmit={this.handleSubmit}>
              <Form.Item>
                {getFieldDecorator('username', {
                  rules: [{ required: true, message: '请输入账号' }],
                })(
                  <Input
                    prefix={<Icon type='user' style={{ color: 'rgba(0,0,0,.25)' }} />}
                    placeholder='账号'
                  />,
                )}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('password', {
                  rules: [{ required: true, message: '请输入密码' }],
                })(
                  <Input
                    prefix={<Icon type='lock' style={{ color: 'rgba(0,0,0,.25)' }} />}
                    type='password'
                    placeholder='密码'
                  />,
                )}
              </Form.Item>
              <Form.Item>
                <Button block loading={loading} type='primary' htmlType='submit' size='large'>登录</Button>
              </Form.Item>
            </Form>
          </Card>
        </div>
      </Provider>
    )
  }

  private initReactRef() {
    this.divRef = React.createRef()
  }

  private async handleSubmit(e: React.FormEvent) {
    e.stopPropagation()
    e.preventDefault()
    const { validateFields } = this.props.form
    await this.setState({ loading: true })
    validateFields(async (err, values: { password: string, username: string }) => {
      if (err) {
        this.setState({ loading: false })
        this.$message.error('请输入登录信息', 5)
        return
      }
      const { password, username } = values
      const { code, data, message } = await this.api.login(username, utils.encrypt(password))
      if (code !== 0) {
        this.setState({ loading: false })
        this.$message.error(message, 5)
        return
      }
      const { token, expireAt } = data
      const { targetUrl } = this.query
      storage.set({ token, expireAt })
      HttpProxy.token = token
      setTimeout(() => {
        this.props.history!.push(targetUrl || '/')
      }, 0)
      this.setState({ loading: false })
    })

  }
}

export default Form.create<LoginProps>({ name: 'login_form' })(Login)

// const { Consumer, Provider } = React.createContext('default')
// ConcurrentMode 整体渲染过程可控, 同时也可以调度, 控制渲染优先级;
// flushSync 提高渲染优先级
// Fiber 记录每一个 react 节点的状态;
